<template>
	<process-frame
		:loading="loading" 
		:error="error" 
		:errorMsg="errorMsg" 
		:empty="!detailInfo" 
		:errorBtn="errorBtn" 
		@errorclick="getInfo"
	>
		<view class="stock-detail" v-if="detailInfo">
			<view class="product-card box-card">
				<custom-image
					:src="detailInfo.picUrl"
					width="160rpx" 
					height="160rpx" 
					radius="12rpx" 
					mode="aspectFill" 
					@click="onReviewImage"
				></custom-image>
				<view class="product-content">
					<view class="product-title">{{ detailInfo.name }}</view>
					<view class="product-label">货号：{{ detailInfo.goodsSn }}</view>
					<view class="product-label">库存：{{ detailInfo.stock }}件</view>
					<view class="product-label">产地：{{ detailInfo.factoryName }}</view>
				</view>
			</view>
			
			<view class="box-card m-t-20" v-for="(item, index) in storeList" :key="item.storeId">
				<view class="store-name m-b-20">{{ item.storeName }} 库存{{ item.stock }}件</view>
				<uni-table border stripe emptyText="该门店暂无此商品">
					<uni-tr>
						<uni-th 
							align="center" 
							filter-type="search" 
							@filter-change="onFilter($event, index)"
						>规格</uni-th>
						<uni-th 
							align="center" 
							width="100" 
							sortable 
							filter-type="range" 
							@sort-change="onSort($event, index)" 
							@filter-change="onFilter($event, index)" 
						>库存</uni-th>
						<uni-th
							v-if="
								userInfo.storeType == StoreType.main && 
								(userInfo.superFlag == SuperFlag || userInfo.postId == PostType.stock)
							" 
							align="center" 
							width="100"
						>标签</uni-th>
					</uni-tr>
					<uni-tr v-for="(s, i) in item.list" :key="i">
						<uni-td align="center">{{ s.productName }}</uni-td>
						<uni-td align="center">{{ s.stock }}</uni-td>
						<uni-td 
							align="center" 
							v-if="
								userInfo.storeType == StoreType.main && 
								(userInfo.superFlag == SuperFlag || userInfo.postId == PostType.stock)
						">
							<button v-if="s.stock > 0" class="custom-btn print-btn" @click="onShowPrinDialog(s)">打印</button>
						</uni-td>
					</uni-tr>
				</uni-table>
			</view>
			<!-- 总店超管或者总店库管 -->
			<view 
				class="p-30" 
				v-if="userInfo.storeType == StoreType.main && (userInfo.superFlag == SuperFlag || userInfo.postId == PostType.stock)">
				<button class="custom-btn submit-btn" @click="toUpdatePage">编 辑</button>
			</view>
			<!-- 打印配置弹窗 -->
			<u-popup 
				:show="showPrinDialog" 
				mode="center" 
				:round="14" 
				:closeOnClickOverlay="false" 
				:safeAreaInsetBottom="false">
				<view class="print-dialog">
					<view class="print-title">打印标签</view>
					<view class="">
						<view class="print-cell">
							<view class="print-cell-label">规格名称</view>
							<view class="print-cell-value">
								<u--input
									v-model="printInfo.productName" 
									:customStyle="{padding: '6px 9px'}" 
									fontSize="30" 
									border="none"  
									readonly 
									placeholderClass="print-inputholder" 
								></u--input>
							</view>
						</view>
						<view class="print-cell">
							<view class="print-cell-label">规格库存</view>
							<view class="print-cell-value">
								<u--input
									v-model="printInfo.stock" 
									:customStyle="{padding: '6px 9px'}" 
									fontSize="30" 
									border="none"  
									readonly 
									placeholderClass="print-inputholder" 
								></u--input>
							</view>
						</view>
						<view class="print-cell">
							<view class="print-cell-label">可打印数</view>
							<view class="print-cell-value">
								<u--input
									v-model="printInfo.canPrintCount" 
									:customStyle="{padding: '6px 9px'}" 
									fontSize="30" 
									border="none"  
									readonly 
									placeholderClass="print-inputholder" 
								></u--input>
							</view>
						</view>
						<view class="print-cell">
							<view class="print-cell-label">打印数量</view>
							<view class="print-cell-value">
								<u--input 
									v-model="printInfo.number" 
									fontSize="30" 
									border="surround" 
									placeholder="请输入打印数量" 
									placeholderClass="print-inputholder" 
								></u--input>
							</view>
						</view>
					</view>
					<view class="print-btns">
						<view class="print-btns-item">
							<u-button
								:customStyle="{'height': '80rpx', 'font-size': '28rpx'}" 
								@click="onClosePrinDialog"
							>关闭</u-button>
						</view>
						<view class="print-gap"></view>
						<view class="print-btns-item">
							<u-button
								color="#0E94FC" 
								:customStyle="{'height': '80rpx', 'font-size': '28rpx'}" 
								:disabled="printDisabled" 
								@click="handlePrint"
							>{{ printInfo.link ? '复制链接' : '生成链接' }}</u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</process-frame>
</template>

<script>
	import processFrame from '@/mixins/process-frame.js'
	import userMixins from '@/mixins/user.js'
	import { deepClone } from '@/utils/util.js'
	import { stockInfo, createPrintLink, subPrintNum } from '@/api/stock.js'
	import { PostType, StoreType, SuperFlag } from '@/utils/enum.js'
	
	const defaultPrintInfo = {
		productId: null,
		productName: '',
		stock: 0,
		canPrintCount: 0,
		number: 0,
		link: '',
	}
	
	export default {
		mixins: [processFrame, userMixins],
		data() {
			return {
				detailInfo: null,
				storeList: [],
				PostType, 
				StoreType, 
				SuperFlag,
				showPrinDialog: false,
				printInfo: deepClone(defaultPrintInfo)
			}
		},
		computed: {
			printDisabled() {
				return !this.printInfo.productId || this.printInfo.number == 0 || this.printInfo.canPrintCount == 0
			}
		},
		onLoad(options) {
			if (!options.stockId) {
				this.loading = false
				this.error = true
				this.errorMsg = '缺少必要参数，无法加载页面'
				this.errorBtn = false
			} else {
				this.stockId = options.stockId
				this.getInfo()
				if (this.token) {
					this.getUserInfo()
				}
			}
			this.$wxSdkUtil.init(null, { hideShare: true })
		},
		methods: {
			// 详情
			async getInfo() {
				try {
					this.loading = true
					this.error = false
					const { data } = await stockInfo(this.stockId)
					data.stock = data.storeStockList.reduce((total, item) => {
						return total + (item.stock || 0)
					}, 0)
					this.detailInfo = data
					this.storeList = data.storeStockList
					this.originStoreList = deepClone(data.storeStockList)
				} catch(error) {
					this.error = true
					this.errorMsg = error.message
				} finally {
					this.loading = false
				}
			},
			// 预览
			onReviewImage() {
				const url = this.detailInfo.picUrl
				uni.previewImage({
					current: url,
					urls: [url]
				})
			},
			// 排序
			onSort(e, storeIndex) {
				const { order } = e
				if (order === 'ascending') {
					this.storeList[storeIndex].list.sort((a, b) => a.stock - b.stock)
				} else if (order === 'descending') {
					this.storeList[storeIndex].list.sort((a, b) => b.stock - a.stock)
				} else {
					this.storeList[storeIndex].list = deepClone(this.originStoreList[storeIndex].list)
				}
			},
			// 过滤
			onFilter(e, storeIndex) {
				console.log(e)
				const { filterType, filter } = e
				if (filterType === 'search') {
					this.onSearch(filter, storeIndex)
				} else if (filterType === 'range') {
					this.onRange(filter, storeIndex)
				}
			},
			// 模糊搜索
			onSearch(filter, storeIndex) {
				const originStockList = deepClone(this.originStoreList[storeIndex].list)
				if (filter === '') {
					this.storeList[storeIndex].list = originStockList
				} else {
					const searchFn = (item) => {
						return item.productName.includes(filter) || filter.includes(item.productName)
					}
					this.storeList[storeIndex].list = originStockList.filter(searchFn)
				}
			},
			// 库存区间
			onRange(filter, storeIndex) {
				const originStockList = deepClone(this.originStoreList[storeIndex].list)
				if (isNaN(filter[0]) && isNaN(filter[1])) {
					this.storeList[storeIndex].list = originStockList
				} else {
					const min = filter[0] || 0
					const max = filter[1] || 999999
					const filterFn = (item) => {
						return item.stock >= min && item.stock <= max
					}
					this.storeList[storeIndex].list = originStockList.filter(filterFn)
				}
			},
			// 编辑
			toUpdatePage() {
				uni.navigateTo({
					url: '/pages/stock/update?stockId=' + this.stockId,
					events: {
						submit: (data) => {
							console.log('update submit')
							this.getInfo()
						}
					}
				})
			},
			// 获取剩余打印数量
			async getSubPrintNum(productId) {
				try {
					uni.showLoading({ title: '获取打印数量', mask: true })
					const { data } = await subPrintNum({ productId })
					uni.hideLoading()
					return data.subPrintNum
				} catch(e) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
			},
			// 显示打印弹窗
			async onShowPrinDialog(info) {
				this.showPrinDialog = true
				
				const skuItem = this.detailInfo.products.find(item => item.sku === info.productName)
				if (!skuItem) {
					return uni.showToast({
						title: '当前规格异常',
						icon: 'none'
					})
				}
				const printInfo = deepClone(defaultPrintInfo)
				printInfo.productId = skuItem.id
				printInfo.productName = info.productName
				printInfo.stock = info.stock
				printInfo.number = 0
				this.printInfo = printInfo
				this.printInfo.canPrintCount = await this.getSubPrintNum(skuItem.id)
			},
			// 关闭打印弹窗
			onClosePrinDialog() {
				this.showPrinDialog = false
			},
			// 生成链接或复制
			async handlePrint() {
				const copyLink = () => {
					uni.setClipboardData({
						data: this.printInfo.link,
						showToast: false,
						success() {
							uni.showToast({
								title: '链接已复制',
								icon: 'success'
							})
						}
					})
				}
				
				if (!this.printInfo.link) {
					if (this.printInfo.number > this.printInfo.canPrintCount) {
						return uni.showToast({
							title: '超出最大可打印数量',
							icon: 'none'
						})
					}
					try {
						uni.showLoading({ title: '正在生成链接', mask: true })
						const { data } = await createPrintLink({
							productId: this.printInfo.productId, 
							number: this.printInfo.number
						})
						this.printInfo.link = data.link
						this.$nextTick(() => copyLink())
					} catch(e) {
						uni.showToast({
							title: e.message,
							icon: 'none'
						})
					}
				} else {
					copyLink()
				}
			}
		}
	}
</script>

<style lang="scss">
	.print-inputholder {
		font-size: 30rpx;
		font-weight: 300;
		line-height: 1.2;
		color: $u-tips-color !important;
	}
</style>

<style lang="scss" scoped>
	.stock-detail {
		padding: 20rpx;
		.box-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
		}
		.product-card {
			display: flex;
			.product-content {
				flex: 1;
				margin-left: 20rpx;
				.product-title {
					font-size: 28rpx;
					font-weight: 500;
					color: $u-main-color;
				}
				.product-label {
					margin-top: 6rpx;
					font-size: 24rpx;
					font-weight: normal;
					color: $u-content-color;
				}
			}
		}
		.store-name {
			font-size: 30rpx;
			font-weight: 500;
			color: $u-main-color;
		}
		.custom-btn {
			margin: 0 auto;
			padding: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 12rpx;
			color: #fff;
			&::after {
				border: none;
			}
		}
		.custom-btn[disabled] {
			background-color: #c8c9cc;
		}
		.submit-btn {
			width: 300rpx;
			height: 80rpx;
			font-size: 30rpx;
			background-color: $u-primary;
		}
		.print-btn {
			width: 120rpx;
			height: 60rpx;
			font-size: 28rpx;
			background-color: $u-primary;
		}
		.print-dialog {
			padding: 30rpx;
			width: 580rpx;
			.print-title {
				font-size: 34rpx;
				font-weight: 500;
				color: #333;
				text-align: center;
			}
			.print-cell {
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				.print-cell-label {
					width: 5em;
					font-size: 30rpx;
					font-weight: normal;
					color: #666;
					text-align: right;
				}
				.print-cell-value {
					flex: 1;
					margin-left: 20rpx;
					font-size: 30rpx;
					font-weight: normal;
					color: #333;
				}
			}
			.print-btns {
				margin-top: 30rpx;
				display: flex;
				&-item {
					flex: 1;
				}
				.print-gap {
					width: 30rpx;
					flex-shrink: 0;
				}
			}
		}
	}
</style>